"""
北交所录入助审系统主应用

FastAPI 主应用入口，提供信息披露智能录入和助审服务
"""

import os
from contextlib import asynccontextmanager
from datetime import datetime

from fastapi import FastAPI, Request, status, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from loguru import logger
from pydantic import BaseModel, ValidationError

from src.api.v1 import api_router
from src.api.v1.endpoints.rule_config_web import router as rule_config_web_router
from src.core.logging import setup_logging


class HealthResponse(BaseModel):
    """健康检查响应模型"""
    status: str
    service: str
    version: str
    timestamp: str


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 初始化日志系统
    debug = os.getenv("DEBUG", "false").lower() == "true"
    log_level = os.getenv("LOG_LEVEL", "INFO").upper()
    
    setup_logging(debug=debug, log_level=log_level)
    
    # 启动时执行
    logger.info("🚀 北交所录入助审系统启动中...")
    logger.info(f"🔧 配置信息: DEBUG={debug}, LOG_LEVEL={log_level}")
    
    # 初始化MinIO对象存储
    try:
        from src.utils.minio.init import initialize_minio
        auto_cleanup_days = int(os.getenv("MINIO_AUTO_CLEANUP_DAYS", "7"))
        initialize_minio(auto_cleanup_days=auto_cleanup_days)
    except Exception as e:
        logger.warning(f"MinIO初始化失败（系统将继续运行）: {str(e)}")
    
    logger.info("📋 已加载功能模块：")
    logger.info("  - 文件质量检测 ✅")
    logger.info("  - 规则配置管理 ✅")
    logger.info("  - PDF高亮标注 ✅")
    logger.info("  - MinIO对象存储 ✅")
    logger.info("  - 字段信息提取 ✅")
    logger.info("  - 规则审核 ✅")
    logger.info("✅ 系统启动完成")
    
    yield
    
    # 关闭时执行
    logger.info("👋 北交所录入助审系统正在关闭...")
    logger.info("✅ 系统已安全关闭")


# 创建FastAPI应用实例
app = FastAPI(
    title="北交所录入助审系统API",
    description="""
    北交所信息披露智能录入和助审系统接口文档
    
    ## 主要功能模块
    - 文件质量检测：支持PDF和图片的清晰度、分辨率、遮挡检测
    - 字段信息提取：从多种文档中提取结构化信息
    - 规则审核：基于配置规则进行智能审核
    - 任务管理：长时间运行任务的查询和管理
    - 规则配置管理：提取和审核规则的配置管理
    
    ## 技术特点
    - RESTful API设计
    - 支持SSE流式响应
    - 统一的响应格式
    - 完善的错误处理
    - JWT身份认证（开发中）
    
    ## 当前版本功能
    - ✅ 文件质量检测API
    - ✅ 字段提取API
    - ✅ 规则审核API
    """,
    version="1.0.0",
    contact={
        "name": "API支持团队", 
        "email": "support@example.com"
    },
    lifespan=lifespan,
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json"
)

# CORS中间件配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件目录（Bootstrap等）
app.mount("/static", StaticFiles(directory="src/templates"), name="static")


# Pydantic验证错误处理器
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """处理请求参数验证错误"""
    logger.warning(f"请求参数验证失败: {str(exc)}")
    
    # 转换Pydantic错误为统一格式
    error_details = []
    for error in exc.errors():
        field_path = " -> ".join(str(loc) for loc in error["loc"][1:])  # 跳过'body'
        error_details.append({
            "field": field_path,
            "message": error["msg"]
        })
    
    return JSONResponse(
        status_code=status.HTTP_400_BAD_REQUEST,
        content={
            "code": 400,
            "message": "Bad Request",
            "error": {
                "error_code": "VALIDATION_ERROR",
                "error_message": "请求参数验证失败",
                "details": error_details
            },
            "timestamp": datetime.utcnow().isoformat() + "Z"
        }
    )


# HTTPException处理器
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    """处理HTTP异常"""
    logger.warning(f"HTTP异常: {exc.status_code} - {str(exc.detail)}")
    
    # 如果detail已经是我们的统一格式，直接使用
    if isinstance(exc.detail, dict) and "error_code" in exc.detail:
        error_info = {
            "error_code": exc.detail.get("error_code", "HTTP_ERROR"),
            "error_message": exc.detail.get("error_message", str(exc.detail))
        }
        if "trace_id" in exc.detail:
            error_info["trace_id"] = exc.detail["trace_id"]
    else:
        # 否则转换为统一格式
        error_info = {
            "error_code": "HTTP_ERROR",
            "error_message": str(exc.detail)
        }
    
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "code": exc.status_code,
            "message": "Error" if exc.status_code >= 500 else "Bad Request",
            "error": error_info,
            "timestamp": datetime.utcnow().isoformat() + "Z"
        }
    )


# 全局异常处理器
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """全局异常处理"""
    logger.error(f"未处理的异常: {str(exc)}", exc_info=True)
    
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={
            "code": 500,
            "message": "Internal Server Error",
            "error": {
                "error_code": "INTERNAL_ERROR",
                "error_message": "服务器内部错误，请稍后重试"
            },
            "timestamp": datetime.utcnow().isoformat() + "Z"
        }
    )


# 根路径健康检查
@app.get(
    "/",
    response_model=HealthResponse,
    summary="系统健康检查",
    description="检查系统是否正常运行"
)
async def root():
    """根路径健康检查"""
    return HealthResponse(
        status="healthy",
        service="北交所录入助审系统",
        version="1.0.0",
        timestamp=datetime.utcnow().isoformat() + "Z"
    )


@app.get(
    "/health",
    response_model=HealthResponse,
    summary="详细健康检查", 
    description="获取系统健康状态详细信息"
)
async def health_check():
    """详细健康检查"""
    return HealthResponse(
        status="healthy",
        service="北交所录入助审系统",
        version="1.0.0", 
        timestamp=datetime.utcnow().isoformat() + "Z"
    )


# 注册API路由
app.include_router(api_router)
# 注册Web界面路由
app.include_router(rule_config_web_router)


# 启动配置
if __name__ == "__main__":
    import uvicorn
    
    # 从环境变量获取配置
    host = os.getenv("HOST", "0.0.0.0")
    port = int(os.getenv("PORT", 8580))
    debug = os.getenv("DEBUG", "false").lower() == "true"
    
    logger.info(f"🌐 启动服务器: http://{host}:{port}")
    logger.info(f"📚 API文档: http://{host}:{port}/docs")
    
    uvicorn.run(
        "src.main:app",
        host=host,
        port=port,
        reload=debug,
        log_level="info" if not debug else "debug"
    )
